""" java libraries """
#from java.awt import Color
#from java.awt import Font
from java.util import Locale
from java.io import File
from java.text import DecimalFormat
from java.lang import String
from java.lang import StringBuilder
from java.lang import Double
#from java.lang import Math
""" aida libraries """
from hep.aida import ITree
from hep.aida import ITuple
from hep.aida import IFunction
from hep.aida import IHistogram
from hep.aida import IDataPointSet
""" jhplot libraries """
#from jhplot.jadraw import JaText
#from jhplot.jadraw import JaKey
#from jhplot  import HPlotJa
#from jhplot  import H1D
#from jhplot  import F1D
#from jhplot  import P1D
""" Philippe's libraries """
from fr.in2p3.ipnl.aidautilities import AidaUtil
""" jscinttools libraries """
from jscinttools.datafit import DataFitter
from jscinttools.datafit import FitSettings
from jscinttools.datafit import FitFuncFactory
from jscinttools.scint import SetupFileReader
from jscinttools.utilities.scintutilities import ScintUtil
from jscinttools.utilities.aidautilities import AidaFileReader
from jscinttools.utilities.aidautilities import AUtil
from jscinttools.utilities.aidautilities import AidaFactories
#from jscinttools.utilities.plotterutilities import BeautifierFactory
#from jscinttools.utilities.plotterutilities import PlotFonts
#from jscinttools.utilities.plotterutilities import PlotColors
#from jscinttools.utilities.plotterutilities import FileExtensions
from jscinttools.utilities.javautilities import MathUtil
from jscinttools.scint.emissionspectrum import EmSpecCorrCalculator

Locale.setDefault(Locale.ENGLISH) #For French OS
af = AidaFactories.ANALYSIS_FACTORY
sff = FitFuncFactory.specFuncFactory()
specFitFunc = sff.nGaussMoyal()
specDF = DataFitter(specFitFunc)

pff = FitFuncFactory.pulseFuncFactory()
pulseFitFunc = pff.nExpBck()
pulseDF = DataFitter(pulseFitFunc)

fileSep = File.separator

#showFigures = False
#writeFigures = not showFigures
writeAida = True

genPath = "/home/marc-antoine/Documents/ZnWO4/Run_9/Reduced/TDC"
aidaName = "Run_9_QF"

day = [ "/2011_07_15/",
	"/2011_07_15/",
	"/2011_07_16/",
	"/2011_07_16/",
	"/2011_07_16/",
	"/2011_07_17/",	
	"/2011_07_17/",
	"/2011_07_17/",
	"/2011_07_18/",
	"/2011_07_18/",
	"/2011_07_18/",
	"/2011_07_18/",
	"/2011_07_19/",
	"/2011_07_19/",
	"/2011_07_19/",
	"/2011_07_19/",
	"/2011_07_19/"]
	
files = ["Am241Cs137_300K_901",
	 "Am241Cs137_250K_901",
	 "Am241Cs137_200K_901",
	 "Am241Cs137_160K_901",	 
	 "Am241Cs137_100K_901",
	 "Am241Cs137_77K_901",
	 "Am241Cs137_50K_901",
	 "Am241Cs137_40K_901",
	 "Am241Cs137_30K_901",
	 "Am241Cs137_20K_901",
	 "Am241Cs137_15K_901",
	 "Am241Cs137_10K_901",
	 "Am241Cs137_8K_901",
	 "Am241Cs137_6K_901",
	 "Am241Cs137_5K_901",
	 "Am241Cs137_4K_901",
	 "Am241Cs137_3400mK_901"]

fileSuffix = "_PhotonReanalysis_NoTuples"
peaks = ["GammaPeak/", "AlphaPeak/"]


treeFac = AidaFactories.TREE_FACTORY
treeName = genPath + fileSep + aidaName
tree = treeFac.createTree(treeName + ".aida", "xml", treeFac.CREATE)
tree.mkdir("Spectra")
tree.mkdir("GammaPeak")
tree.mkdir("AlphaPeak")

tree.cd("/Spectra")
tupFac = af.createTupleFactory(tree)
tupColB = StringBuilder()
tupColB.append("double Temper_K, ")
tupColB.append("double AmpG0, double AmpG0Err, ")
tupColB.append("double muG0, double muG0Err, ")
tupColB.append("double sigG0, double sigG0Err, ")
tupColB.append("double AmpG1, double AmpG1Err, ")
tupColB.append("double muG1, double muG1Err, ")
tupColB.append("double sigG1, double sigG1Err, ")
tupColB.append("double AmpG2, double AmpG2Err, ")
tupColB.append("double muG2, double muG2Err, ")
tupColB.append("double sigG2, double sigG2Err, ")
tupColB.append("double AmpG3, double AmpG3Err, ")
tupColB.append("double muG3, double muG3Err, ")
tupColB.append("double sigG3, double sigG3Err, ")
tupColB.append("double AmpM, double AmpMErr, ")
tupColB.append("double muM, double muMErr, ")
tupColB.append("double sigM, double sigMErr, ")
tupColB.append("Chi2")
tup = tupFac.create("SpecFit", "SpecFit", tupColB.toString())

pulseTupColB = StringBuilder()
pulseTupColB.append("double Temper_K, ")
pulseTupColB.append("double A0, double A0Err, ")
pulseTupColB.append("double tau0, double tau0Err, ")
pulseTupColB.append("double A1, double A1Err, ")
pulseTupColB.append("double tau1, double tau1Err, ")
pulseTupColB.append("double A2, double A2Err, ")
pulseTupColB.append("double tau2, double tau2Err, ")
pulseTupColB.append("double P0, double P0Err, ")
pulseTupColB.append("Chi2")

tree.cd("/GammaPeak")
gPulseTup = tupFac.create("gammaPulseFit", "gammaPulseFit", pulseTupColB.toString())
tree.cd("/AlphaPeak")
aPulseTup = tupFac.create("alphaPulseFit", "alphaPulseFit", pulseTupColB.toString())


histoFac = af.createHistogramFactory(tree)
histoFullName = "Reanalysis/Ch2 Plus Ch1 Total Photons,Some Cuts"
avEvtPath = "Reanalysis/Average pulse shapes/Variable binning/Special Bin, Average Pulse from First Photon on Ch2, Ch1, All Cuts"

funcFac = af.createFunctionFactory(tree)

dpsFac = af.createDataPointSetFactory(tree)

tree.cd("..")
qfDPS = dpsFac.create("agQF", 2)
qfNormDPS = dpsFac.create("agQFNorm", 2)
lyGammaDPS = dpsFac.create("Cs137_LY", 2)
lyAlphaDPS = dpsFac.create("Am241_LY", 2)
kinGammaDPS = dpsFac.create("Cs137_Kin", 2)
kinAlphaDPS = dpsFac.create("Am241_Kin", 2)

gScalFac = 1.0
gScalFacErr = 0.0
aScalFac = 1.0 
aScalFacErr = 0.0
qfScaleFac = 1.0
qfScaleFacErr = 0.0

loop = len(files)

avEvt = []
avEvtHist = []

eG_kev = 662.0
eA_kev = 5486.0
acqWin_us = 1800.0

source = ""
peak = ""

""" Vitalii's Curve """
#afrEmSpec = AidaFileReader("/home/marc-antoine/Documents/ZnWO4/Emission_Spectra", "ZnWO4_EmissionSpectra")
#emSpecDPS = afrEmSpec.grabDPS("30eV_Hasylab/corrFacNorm")

""" LPCML Curve """
afrEmSpec = AidaFileReader("/home/marc-antoine/Documents/LPCML/2011_09_23/ZnWO4/", "ZnWO4_XRaysSpectraLPCML")
emSpecDPS = afrEmSpec.grabDPS("LY_Norm")
emSpecCorrCalc = EmSpecCorrCalculator(emSpecDPS)

#prelim = JaText("PRELIMINARY", 0.05, 0.35, "NDC")
#prelim.setFont(PlotFonts.SF_B_30)
#prelim.setColor(Color.RED)
#prelim.setRotAngle(-45)

fmt = DecimalFormat("#.##")
fmtSc = DecimalFormat("0.00E0")

for i in range(loop):
	tempName = files[i].split("7_")[1].split("K_")[0]
	print "\n\n\n==============================================================="
	print "\tRun 9 Analysis - T = " + tempName + " K"
	print "==============================================================="
	print "\n+++++++++++++++++++++++++++"
	print peak + "Spectrum Analysis"
	print "+++++++++++++++++++++++++++"
	afr = AidaFileReader(genPath + day[i], files[i] + fileSuffix)
	tree.cd("/Spectra")
	specHisto = histoFac.createCopy(tempName + "K", afr.grabHisto1D(histoFullName))
	normFac = AUtil.maxBinHeight(specHisto, [200, 400])
	specHisto.scale(1.0 / normFac)
	
	sfr = SetupFileReader(genPath + day[i], files[i] + ".setup")
	specStartPar = sfr.findParamValues("Total Spectrum fit Parameters")
	
	fs = FitSettings(specStartPar)
	fitRes = specDF.doFit(specHisto, fs)
	print "\nFitting Spectrum" 
	print(AidaUtil.printResultsOfFit(fitRes))
	specIFunc = funcFac.cloneFunction("FitFunc_" + tempName + "K", fitRes.fittedFunction())
	
	fitVal = fitRes.fittedParameters()
	fitValErr = fitRes.errors()
	chi2 = fitRes.quality()
	
	
	#fitResValF = []
	#fitResValErrF = []
	#fitResStr = []
	#for j in range(len(fitVal)):
	#	fitResValF.append(fmt.format(fitVal[j]))
	#	fitResValErrF.append(fmt.format(fitValErr[j]))
	#	fitResStr.append(fitResValF[j] + " &plusmn; " + fitResValErrF[j])
	#chi2ValF = fmt.format(chi2)
	#
	#statLine = []
	#statLine.append("Amp = " + fitResStr[0])
	#statLine.append("&micro; = " + fitResStr[1])
	#statLine.append("&sigma; = " + fitResStr[2])
	#statBox = [] #Some Fit Results
	#for j in range (len(statLine)):
	#	statBox.append(JaText(statLine[j], 0.6, 0.375+(j*0.035), "NDC"))
	#	statBox[j].setFont(PlotFonts.STATBOX_FONT)
	#	statBox[j].setColor(Color.BLACK)
	#	
	#statLine2 = []
	#statLine2.append("Amp = " + fitResStr[3])
	#statLine2.append("&micro; = " + fitResStr[4])
	#statLine2.append("&sigma; = " + fitResStr[5])
	#statBox2 = [] #Some Other Fit Results
	#for j in range (len(statLine2)):
	#	statBox2.append(JaText(statLine2[j], 0.35, 0.5+(j*0.035), "NDC"))
	#	statBox2[j].setFont(PlotFonts.STATBOX_FONT)
	#	statBox2[j].setColor(Color.BLACK)
	
	tempVal = 0
	if tempName.endswith("m"):
		tempVal = Double.valueOf(tempName.split("m")[0]) / 1000.0
	else:
		tempVal = Double.valueOf(tempName)
	#yMax = 0
	#maxBin = specHisto.maxBinHeight()
	#ceilMaxBin = Math.ceil(maxBin)
	#if ((ceilMaxBin - maxBin) > 0.5):
	#	yMax = ceilMaxBin - 0.5
	#else:
	#	yMax = ceilMaxBin
	#specTitle = "ZnWO_{4}, Spectrum at T = " + String.valueOf(tempVal) + " K"
	#spec = H1D(specHisto)
	#spec.setTitle(specTitle)
	#spec.setColor(Color.BLUE)
	#spec.setStyle("h")
	#spec.setPenWidth(2)
	#spec.setErrAll(False)
	#
	#specFunc = F1D(specIFunc)
	#specFunc.setTitle(specTitle)
	#specFunc.setMin(10000)
	#specFunc.setColor(Color.RED)
	#specFunc.setPenWidth(2)
	#specFunc.setMin(0)
	#specFunc.setMax(400)
	#
	#
	#specPlotter = HPlotJa(specTitle, 600, 600, 1, 1, True)
	#specPlotter.setGTitle(specTitle, PlotFonts.TITLE_FONT)
	#specPlotter.setAntiAlias(False)
	#specPlotter.visible(showFigures)
	#specPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
	#specPlotter.setRange(0, 400, 0, yMax)
	#specPlotter.setTicFont(PlotFonts.TICK_FONT)
	#specPlotter.setShowStatBox(False)
	#specPlotter.showKey(False)
	#specPlotter.setNameX("Number of Photons")
	#specPlotter.setNameY("Counts (a.u.)")
	#specPlotter.draw(spec)
	#specPlotter.draw(specFunc)
	#specPlotter.draw(prelim)
	#for j in range (len(statLine)):
	#	specPlotter.draw(statBox[j])
	#for j in range (len(statLine2)):
	#	specPlotter.draw(statBox2[j])
	#specPlotter.update()
	#
	#pbSpec = BeautifierFactory.beautifyHPlotJa(specPlotter)
	#specPad11 = pbSpec.pad(1, 1)
	#specLabelX11 = specPad11.axisLabel(0)
	#specLabelX11.centerLabel(0.0)
	#specLabelX11.changeFont(PlotFonts.AXIS_LABEL_FONT)
	#specLabelY11 = specPad11.axisLabel(1)
	#specLabelY11.centerLabel(-0.00)
	#specLabelY11.changeFont(PlotFonts.AXIS_LABEL_FONT)
	#
	#specTickLabX11 = specPad11.tickLabel(0)
	#specTickLabX11.axisDistance(0.0)
	#specTickLabX11.removeNegativeZero()
	#specTickLabY11 = specPad11.tickLabel(1)
	#specTickLabY11.axisDistance(-0.00)
	#specTickLabY11.removeNegativeZero()
	#
	#specPlotter.update()
	#if writeFigures:
	#	for j in range(len(FileExtensions.FIG_TYPES)):
	#		outFileName = "ZnWO4_Spectrum_" + tempName + "K" + FileExtensions.FIG_TYPES[j]
	#		specPlotter.export(genPath + File.separator + outFileName)
	#		print("Writting File : " + genPath + File.separator + outFileName)
	
	
	tupVal = []
	tupVal.append(tempVal)
	for j in range(len(fitVal)):
		tupVal.append(fitVal[j])
		tupVal.append(fitValErr[j])
		
	tupVal.append(chi2)
	tup.fill(tupVal)
	tup.addRow()
	
	gammaCorr = 0
	gammaCorrErr = 0
	alphaCorr = 0
	alphaCorrErr = 0
	
	for j in range(len(peaks)):
		if (peaks[j] == "GammaPeak/"):
			source = "^{137}Cs &gamma;-"
			peak = "Gamma"
			tree.cd("/GammaPeak")
		elif (peaks[j] == "AlphaPeak/"):
			source = "^{241}Am &alpha;-"
			peak = "Alpha"
			tree.cd("/AlphaPeak")

		print "\n\n+++++++++++++++++++++++++++"
		print peak + "-Peak Analysis"
		print "+++++++++++++++++++++++++++"
		afrPeak = AidaFileReader(genPath + day[i] + peaks[j], files[i] + fileSuffix)
		avEvtHist = histoFac.createCopy("AvPulse_" + tempName + "K", afrPeak.grabHisto1D(avEvtPath))
		histScalFac = avEvtHist.maxBinHeight()
		avEvtHist.scale(1.0 / histScalFac)
		sfrPeak = SetupFileReader(genPath + day[i] + peaks[j], files[i] + ".setup")
		pulseStartPar = sfrPeak.findParamValues("Average Pulse Fit Parameters")
		
		pulseFS = FitSettings(pulseStartPar)
		pulseFitRes = pulseDF.doFit(avEvtHist, pulseFS)
		print "\nFitting Average Pulse" 
		print AidaUtil.printResultsOfFit(pulseFitRes)
		
		pulseFitVal = pulseFitRes.fittedParameters()
		pulseFitValErr = pulseFitRes.errors()
		pulseChi2 = pulseFitRes.quality()
		
		
		amp = [pulseFitVal[0], pulseFitVal[2], pulseFitVal[4]]
		ampErr = [pulseFitValErr[0], pulseFitValErr[2], pulseFitValErr[4]]
		tau = [pulseFitVal[1], pulseFitVal[3], pulseFitVal[5]]
		tauErr = [pulseFitValErr[1], pulseFitValErr[3], pulseFitValErr[5]]
		
		#fnLY = []
		#fnLYErr = []
		#for k in range(3):
		#	fnLY.append(ScintUtil.calcLYFrac(k, amp, tau))
		#	fnLYErr.append(ScintUtil.calcLYFracErr(k, amp, ampErr, tau, tauErr))
		#
		#fitResValF = []
		#fitResValErrF = []
		#fitResStr = []
		#for k in range(3):
		#	fitResValF.append(fmt.format(fnLY[k]))
		#	fitResValF.append(fmt.format(tau[k]))
		#	fitResValErrF.append(fmt.format(fnLYErr[k]))
		#	fitResValErrF.append(fmt.format(tauErr[k]))
		#fitResValF.append(fmt.format(pulseFitVal[6]))
		#fitResValErrF.append(fmt.format(pulseFitValErr[6]))
		#
		#for k in range(len(fitResValF)):
		#	fitResStr.append(fitResValF[k] + " &plusmn; " + fitResValErrF[k])
		#chi2ValF = fmt.format(chi2)
		#
		#statLine = []
		#statLine.append("fn_{0} = " + fitResStr[0])
		#statLine.append("&tau;_{0} = " + fitResStr[1] + " &micro;s")
		#statLine.append("fn_{1} = " + fitResStr[0])
		#statLine.append("&tau;_{1} = " + fitResStr[1] + " &micro;s")
		#statLine.append("fn_{2} = " + fitResStr[0])
		#statLine.append("&tau;_{2} = " + fitResStr[1] + " &micro;s")
		#statLine.append("P_{0} = " + fitResStr[1])
		#statLine.append("&chi;^{2} = " + chi2ValF)
		#
		#statBox = [] #Some Fit Results
		#for k in range (len(statLine)):
		#	statBox.append(JaText(statLine[k], 0.175, 0.575 + (k * 0.035), "NDC"))
		#	statBox[k].setFont(PlotFonts.STATBOX_FONT)
		#	statBox[k].setColor(Color.BLACK)
		
		pulseTupVal = []
		pulseTupVal.append(tempVal)
		for k in range(len(pulseFitVal)):
			pulseTupVal.append(pulseFitVal[k])
			pulseTupVal.append(pulseFitValErr[k])
		pulseTupVal.append(pulseChi2)
		
		if (peaks[j] == "GammaPeak/"):
			gPulseTup.fill(pulseTupVal)
			gPulseTup.addRow()
			gammaCorr = ScintUtil.calcLYCorr(amp, tau, acqWin_us)
			gammaCorrErr = ScintUtil.calcLYCorrErr(amp, ampErr, tau, tauErr, acqWin_us)
			kinGammaPt = kinGammaDPS.addPoint()
			kinGammaPtX = kinGammaPt.coordinate(0)
			kinGammaPtX.setValue(tempVal)
			kinGammaPtY = kinGammaPt.coordinate(1)
			kinGammaPtY.setValue(tau[2])
			kinGammaPtY.setErrorMinus(tauErr[2])
			kinGammaPtY.setErrorPlus(tauErr[2])
		elif (peaks[j] == "AlphaPeak/"):
			aPulseTup.fill(pulseTupVal)
			aPulseTup.addRow()
			alphaCorr = ScintUtil.calcLYCorr(amp, tau, acqWin_us)
			alphaCorrErr = ScintUtil.calcLYCorrErr(amp, ampErr, tau, tauErr, acqWin_us)
			kinAlphaPt = kinAlphaDPS.addPoint()
			kinAlphaPtX = kinAlphaPt.coordinate(0)
			kinAlphaPtX.setValue(tempVal)
			kinAlphaPtY = kinAlphaPt.coordinate(1)
			kinAlphaPtY.setValue(tau[2])
			kinAlphaPtY.setErrorMinus(tauErr[2])
			kinAlphaPtY.setErrorPlus(tauErr[2])
		
		#avEvt = H1D(avEvtHist)	
		#avEvt.setTitle("ZnWO_{4} " + source + "Peak, Pulse at T = " + String.valueOf(tempVal) + " K")
		#avEvt.setColor(Color.BLUE)
		#avEvt.setStyle("h")
		#avEvt.setPenWidth(2)
		#avEvt.setErrAll(False)
		
		iFunc = funcFac.cloneFunction("AvEvt_" + tempName + "K", pulseFitRes.fittedFunction())
		
		#win = sfrPeak.findParamValues("Av Pulse Window (Xmin, Xmax, Ymin, Ymax)")
		#winZoom = sfrPeak.findParamValues("Av Pulse Zoom Window (Xmin, Xmax, Ymin, Ymax)")
		#
		#func = F1D(iFunc)
		#func.setTitle(avEvt.getTitle())
		#func.setMin(10000)
		#func.setColor(Color.RED)
		#func.setPenWidth(2)
		#func.setMin(win[0])
		#func.setMax(win[1])
		#
		#funcZoom = F1D(iFunc)
		#funcZoom.setTitle(avEvt.getTitle())
		#funcZoom.setMin(10000)
		#funcZoom.setColor(Color.RED)
		#funcZoom.setPenWidth(2)
		#funcZoom.setMin(winZoom[0])
		#funcZoom.setMax(winZoom[1])
		#
		#title = avEvt.getTitle()
		#plotter = HPlotJa(title, 600, 600, 2, 1, True)
		#plotter.setGTitle(title, PlotFonts.TITLE_FONT)
		#plotter.setAntiAlias(False)
		#plotter.visible(showFigures)
		#
		#plotter.cd(1,1)	
		#plotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
		#plotter.setRange(win[0], win[1], win[2], win[3])
		#plotter.setLogScale(0, False)
		#plotter.setLogScale(1, True)
		#plotter.setTicFont(PlotFonts.TICK_FONT)
		#plotter.setShowStatBox(False)
		#plotter.showKey(False)
		#plotter.setNameX("Time (&micro;s)")
		#plotter.setNameY("Photons / Time Unit")
		#
		#plotter.cd(2,1)	
		#plotter.setPad(2, 1, 0.525, 0.17, 0.3, 0.3)
		#plotter.setRange(winZoom[0], winZoom[1], winZoom[2], winZoom[3])
		#plotter.setLogScale(0, False)
		#plotter.setLogScale(1, True)
		#plotter.setTicFont(PlotFonts.TICK_FONT)
		#plotter.setShowStatBox(False)
		#plotter.showKey(False)
		#plotter.setNameX("")
		#plotter.setNameY("")
		#
		#""" Plots all the JHep objects"""
		#plotter.cd(1,1)
		#plotter.draw(avEvt)
		#plotter.draw(func)
		#plotter.draw(prelim)
		#for k in range (len(statLine)):
		#	plotter.draw(statBox[k])
		#	
		#plotter.cd(2,1)
		#plotter.draw(avEvt)
		#plotter.draw(funcZoom)
		#
		#plotter.update()
		#
		#pb = BeautifierFactory.beautifyHPlotJa(plotter)
		#pad11 = pb.pad(1, 1)
		#labelX11 = pad11.axisLabel(0)
		#labelX11.centerLabel(0.0)
		#labelX11.changeFont(PlotFonts.AXIS_LABEL_FONT)
		#labelY11 = pad11.axisLabel(1)
		#labelY11.centerLabel(-0.005)
		#labelY11.changeFont(PlotFonts.AXIS_LABEL_FONT)
		#
		#tickLabX11 = pad11.tickLabel(0)
		#tickLabX11.axisDistance(0.0)
		#tickLabX11.removeNegativeZero()
		#tickLabY11 = pad11.tickLabel(1)
		#tickLabY11.axisDistance(-0.00)
		#tickLabY11.displayAsPowerOfTen()
		#
		#pad21 = pb.pad(2, 1)
		#labelX21 = pad21.axisLabel(0)
		#labelX21.centerLabel(0.0)
		#labelX21.changeFont(PlotFonts.AXIS_LABEL_FONT)
		#labelY21 = pad21.axisLabel(1)
		#labelY21.centerLabel(-0.01)
		#labelY21.changeFont(PlotFonts.AXIS_LABEL_FONT)
		#
		#tickLabX21 = pad21.tickLabel(0)
		#tickLabX21.axisDistance(0.0)
		#tickLabX21.removeNegativeZero()
		#tickLabX21.displayAsDecimal("0.0")
		#tickLabY21 = pad21.tickLabel(1)
		#tickLabY21.axisDistance(-0.01)
		#tickLabY21.displayAsPowerOfTen()
        	#
		#plotter.update()
		#if writeFigures:
		#	for k in range(len(FileExtensions.FIG_TYPES)):
		#		outFileName = "ZnWO4_AvPulse_" + peak + "_" + tempName + "K" + FileExtensions.FIG_TYPES[k]
		#		plotter.export(genPath + File.separator + outFileName)
		#		print("Writting File : " + genPath + File.separator + outFileName)

	
	"""
	emSpecCorr = emSpecCorrCalc.extrapolCorrFac(tempVal)
	#print emSpecCorr
	aMean = fitVal[1] * alphaCorr / emSpecCorr
	aErr = MathUtil.uncorrProdErr(fitVal[1], fitValErr[1], alphaCorr, alphaCorrErr)
	gMean = fitVal[4] * gammaCorr / emSpecCorr
	gErr = MathUtil.uncorrProdErr(fitVal[4], fitValErr[4], gammaCorr, gammaCorrErr)
	qf = (aMean / eA_kev) / (gMean / eG_kev)
	qfErr = MathUtil.uncorrRatioErr(aMean/eA_kev, aErr/eA_kev, gMean/eG_kev, gErr/eG_kev)
	
	qfPt = qfDPS.addPoint()
	qfPtX = qfPt.coordinate(0)
	qfPtX.setValue(tempVal)
	qfPtY = qfPt.coordinate(1)
	qfPtY.setValue(qf)
	qfPtY.setErrorMinus(qfErr)
	qfPtY.setErrorPlus(qfErr)
	
	if i == 0:
		gScalFac = fitVal[4]
		aScalFac = fitVal[1]
		qfScaleFac = qf
		
	qfPtNorm = qfNormDPS.addPoint()
	qfPtNormX = qfPtNorm.coordinate(0)
	qfPtNormX.setValue(tempVal)
	qfPtNormY = qfPtNorm.coordinate(1)
	qfPtNormY.setValue(qf / qfScaleFac)
	qfPtNormY.setErrorMinus(qfErr / qfScaleFac)
	qfPtNormY.setErrorPlus(qfErr / qfScaleFac)
	
	gPt = lyGammaDPS.addPoint()
	gPtX = gPt.coordinate(0)
	gPtX.setValue(tempVal)
	gPtY = gPt.coordinate(1)
	gPtY.setValue(gMean / gScalFac)
	gPtY.setErrorMinus(gErr / gScalFac)
	gPtY.setErrorPlus(gErr / gScalFac)
	
	aPt = lyAlphaDPS.addPoint()
	aPtX = aPt.coordinate(0)
	aPtX.setValue(tempVal)
	aPtY = aPt.coordinate(1)
	aPtY.setValue(aMean / aScalFac)
	aPtY.setErrorMinus(aErr / aScalFac)
	aPtY.setErrorPlus(aErr / aScalFac)
	"""
	
	emSpecCorr = emSpecCorrCalc.extrapolCorrFacAndErr(tempVal)
	sCorr = emSpecCorr.value()
	sCorrErr = emSpecCorr.errorPlus()
	#print emSpecCorr
	aMean = fitVal[1] * alphaCorr
	aErr = MathUtil.uncorrProdErr(fitVal[1], fitValErr[1], alphaCorr, alphaCorrErr)
	gMean = fitVal[4] * gammaCorr
	gErr = MathUtil.uncorrProdErr(fitVal[4], fitValErr[4], gammaCorr, gammaCorrErr)
	enRatio = eA_kev / eG_kev
	lyRatio = aMean / gMean
	lyRatioErr = MathUtil.uncorrRatioErr(aMean, aErr, gMean, gErr)
	qf = lyRatio / enRatio
	qfErr = lyRatioErr / enRatio
	
	qfPt = qfDPS.addPoint()
	qfPtX = qfPt.coordinate(0)
	qfPtX.setValue(tempVal)
	qfPtY = qfPt.coordinate(1)
	qfPtY.setValue(qf)
	qfPtY.setErrorMinus(qfErr)
	qfPtY.setErrorPlus(qfErr)
	
	if i == 0:
		gScalFac = gMean / sCorr
		gScalFacErr = MathUtil.uncorrRatioErr(gMean, gErr, sCorr, sCorrErr)
		aScalFac = aMean / sCorr
		aScalFacErr = MathUtil.uncorrRatioErr(aMean, aErr, sCorr, sCorrErr)
		qfScaleFac = qf
		qfScaleFacErr = qfErr
		
	qfPtNorm = qfNormDPS.addPoint()
	qfPtNormX = qfPtNorm.coordinate(0)
	qfPtNormX.setValue(tempVal)
	qfPtNormY = qfPtNorm.coordinate(1)
	qfPtNormY.setValue(qf / qfScaleFac)
	qfPtErr = MathUtil.uncorrRatioErr(qf, qfErr, qfScaleFac, qfScaleFacErr)
	qfPtNormY.setErrorMinus(qfPtErr)
	qfPtNormY.setErrorPlus(qfPtErr)
	
	gPt = lyGammaDPS.addPoint()
	gPtX = gPt.coordinate(0)
	gPtX.setValue(tempVal)
	gPtY = gPt.coordinate(1)
	gcv = gMean / sCorr
	gcvErr = MathUtil.uncorrRatioErr(gMean, gErr, sCorr, sCorrErr)
	gscv = gcv / gScalFac
	gscvErr = MathUtil.uncorrRatioErr(gcv, gcvErr, gScalFac, gScalFacErr)
	gPtY.setValue(gscv)
	gPtY.setErrorMinus(gscvErr)
	gPtY.setErrorPlus(gscvErr)
	
	aPt = lyAlphaDPS.addPoint()
	aPtX = aPt.coordinate(0)
	aPtX.setValue(tempVal)
	aPtY = aPt.coordinate(1)
	acv = aMean / sCorr
	acvErr = MathUtil.uncorrRatioErr(aMean, aErr, sCorr, sCorrErr)
	ascv = acv / aScalFac
	ascvErr = MathUtil.uncorrRatioErr(acv, acvErr, aScalFac, aScalFacErr)
	aPtY.setValue(ascv)
	aPtY.setErrorMinus(ascvErr)
	aPtY.setErrorPlus(ascvErr)

#keyInitY = 0.35
#
#gammaLY = P1D(lyGammaDPS)
#gammaLY.setTitle("137Cs &gamma;")
#gammaLY.setColor(Color.BLUE)
#gammaLY.setStyle("p")
#gammaLY.setSymbol(0)
#gammaLY.setSymbolSize(16)
#gammaLY.setErrX(False)
#gammaLYKey = JaKey(gammaLY.getSymbol(), gammaLY.getTitle(), 0.2, keyInitY + 0.1, "NDC")
#gammaLYKey.setFont(PlotFonts.LEGEND_FONT)
#gammaLYKey.setColor(gammaLY.getColor())
#gammaLYKey.setKeyColor(gammaLY.getColor())
#
#alphaLY = P1D(lyAlphaDPS)
#alphaLY.setTitle("241Am &alpha;")
#alphaLY.setColor(Color.RED)
#alphaLY.setStyle("p")
#alphaLY.setSymbol(2)
#alphaLY.setSymbolSize(16)
#alphaLY.setErrX(False)
#alphaLYKey = JaKey(alphaLY.getSymbol(), alphaLY.getTitle(), 0.2, keyInitY + 0.05, "NDC")
#alphaLYKey.setFont(PlotFonts.LEGEND_FONT)
#alphaLYKey.setColor(alphaLY.getColor())
#alphaLYKey.setKeyColor(alphaLY.getColor())
#
#oxAlphaLYx = [8.0, 15.0, 30.0, 60.0, 95.0, 120.0, 150.0, 180.0, 210.0, 240.0, 270.0, 300.0]
#oxAlphaLYy = [2.895, 2.895, 2.895, 2.868, 2.684, 2.421, 2.316, 2.237, 1.974, 1.632, 1.421, 1.000]
#oxAlphaLYP1D = P1D("Oxford &alpha;", oxAlphaLYx, oxAlphaLYy)
#oxAlphaLYP1D.setStyle("p")
#oxAlphaLYP1D.setColor(Color.BLACK)
#oxAlphaLYP1D.setSymbol(4)
#oxAlphaLYP1D.setSymbolSize(16)
#oxAlphaLYP1D.setErrAll(False)
#oxAlphaLYP1DKey = JaKey(oxAlphaLYP1D.getSymbol(), oxAlphaLYP1D.getTitle(), 0.2, keyInitY, "NDC")
#oxAlphaLYP1DKey.setFont(PlotFonts.LEGEND_FONT)
#oxAlphaLYP1DKey.setColor(oxAlphaLYP1D.getColor())
#oxAlphaLYP1DKey.setKeyColor(oxAlphaLYP1D.getColor())
#
#afrRun4 = AidaFileReader("/home/marc-antoine/Documents/ZnWO4/Run_4", "ScintillationAnalysis_ZnWO4_Txt")
#na22DPS = afrRun4.grabDPS("Light_Yield/LY_Corr")
#na22LY = P1D(na22DPS)
#na22LY.setTitle("22Na &gamma;")
#na22LY.setColor(PlotColors.DARK_GREEN)
#na22LY.setStyle("p")
#na22LY.setSymbol(8)
#na22LY.setSymbolSize(16)
#na22LY.setErrX(False)
#na22LYKey = JaKey(na22LY.getSymbol(), na22LY.getTitle(), 0.2, keyInitY + 0.15, "NDC")
#na22LYKey.setFont(PlotFonts.LEGEND_FONT)
#na22LYKey.setColor(na22LY.getColor())
#na22LYKey.setKeyColor(na22LY.getColor())
#
#lyPlotter = HPlotJa("ZnWO4 LY", 600, 600, 1, 1, True)
#lyPlotter.setGTitle("LY of ZnWO_{4}", PlotFonts.TITLE_FONT)
#lyPlotter.setAntiAlias(False)
#lyPlotter.visible(showFigures)
#lyPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
#lyPlotter.setRange(1, 1000, 0.75, 3.25)
#lyPlotter.setLogScale(0, True)
#lyPlotter.setTicFont(PlotFonts.TICK_FONT)
#lyPlotter.setShowStatBox(False)
#lyPlotter.showKey(False)
#lyPlotter.setNameX("Temperature (K)")
#lyPlotter.setNameY("LY normalized to 300 K")
#lyPlotter.draw(oxAlphaLYP1D)
#lyPlotter.draw(na22LY)
#lyPlotter.draw(gammaLY)
#lyPlotter.draw(alphaLY)
#lyPlotter.draw(oxAlphaLYP1DKey)
#lyPlotter.draw(na22LYKey)
#lyPlotter.draw(gammaLYKey)
#lyPlotter.draw(alphaLYKey)
#lyPlotter.draw(prelim)
#lyPlotter.update()
#
#pbLY = BeautifierFactory.beautifyHPlotJa(lyPlotter)
#lyPad11 = pbLY.pad(1, 1)
#lyLabelX11 = lyPad11.axisLabel(0)
#lyLabelX11.centerLabel(0.0)
#lyLabelX11.changeFont(PlotFonts.AXIS_LABEL_FONT)
#lyLabelY11 = lyPad11.axisLabel(1)
#lyLabelY11.centerLabel(-0.005)
#lyLabelY11.changeFont(PlotFonts.AXIS_LABEL_FONT)
#
#lyTickLabX11 = lyPad11.tickLabel(0)
#lyTickLabX11.axisDistance(0.0)
#lyTickLabX11.displayAsPowerOfTen()
#lyTickLabY11 = lyPad11.tickLabel(1)
#lyTickLabY11.axisDistance(-0.00)
#lyTickLabY11.removeNegativeZero()
#
#lyPlotter.update()
#if writeFigures:
#	for j in range(len(FileExtensions.FIG_TYPES)):
#		outFileName = "ZnWO4_LY" + FileExtensions.FIG_TYPES[j]
#		lyPlotter.export(genPath + File.separator + outFileName)
#		print("Writting File : " + genPath + File.separator + outFileName)
#
#agQF = P1D(qfDPS)
#agQF.setTitle("&alpha;/&gamma; Quenching Factor")
#agQF.setColor(Color.BLUE)
#agQF.setStyle("p")
#agQF.setSymbol(0)
#agQF.setSymbolSize(10)
#agQF.setErrX(False)
##agQFKey = JaKey(agQF.getSymbol(), agQF.getTitle(), 0.5, 0.2, "NDC")
##agQFKey.setFont(PlotFonts.LEGEND_FONT)
##agQFKey.setColor(agQF.getColor())
##agQFKey.setKeyColor(agQF.getColor())
#
#qfPlotter = HPlotJa("ZnWO4 &alpha;/&gamma; Quenching Factor", 600, 600, 1, 1, True)
#qfPlotter.setGTitle("ZnWO_{4} &alpha;/&gamma; Quenching Factor", PlotFonts.TITLE_FONT)
#qfPlotter.setAntiAlias(False)
#qfPlotter.visible(showFigures)
#qfPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
#qfPlotter.setRange(1, 1000, 0.17, 0.21)
#qfPlotter.setLogScale(0, True)
#qfPlotter.setTicFont(PlotFonts.TICK_FONT)
#qfPlotter.setShowStatBox(False)
#qfPlotter.showKey(False)
#qfPlotter.setNameX("Temperature (K)")
#qfPlotter.setNameY("&alpha;/&gamma; Quenching Factor")
#qfPlotter.draw(agQF)
#qfPlotter.draw(prelim)
#qfPlotter.update()
#
#pbQF = BeautifierFactory.beautifyHPlotJa(qfPlotter)
#qfPad11 = pbQF.pad(1, 1)
#qfLabelX11 = qfPad11.axisLabel(0)
#qfLabelX11.centerLabel(0.0)
#qfLabelX11.changeFont(PlotFonts.AXIS_LABEL_FONT)
#qfLabelY11 = qfPad11.axisLabel(1)
#qfLabelY11.centerLabel(-0.005)
#qfLabelY11.changeFont(PlotFonts.AXIS_LABEL_FONT)
#
#qfTickLabX11 = qfPad11.tickLabel(0)
#qfTickLabX11.axisDistance(0.0)
#qfTickLabX11.displayAsPowerOfTen()
#qfTickLabY11 = qfPad11.tickLabel(1)
#qfTickLabY11.axisDistance(-0.00)
#qfTickLabY11.removeNegativeZero()
#
#qfPlotter.update()
#if writeFigures:
#	for j in range(len(FileExtensions.FIG_TYPES)):
#		outFileName = "ZnWO4_agQF" + FileExtensions.FIG_TYPES[j]
#		qfPlotter.export(genPath + File.separator + outFileName)
#		print("Writting File : " + genPath + File.separator + outFileName)
#
#kinGamma = P1D(kinGammaDPS)
#kinGamma.setTitle("137Cs &gamma;")
#kinGamma.setColor(Color.BLUE)
#kinGamma.setStyle("p")
#kinGamma.setSymbol(0)
#kinGamma.setSymbolSize(16)
#kinGamma.setErrX(False)
#kinGammaKey = JaKey(kinGamma.getSymbol(), kinGamma.getTitle(), 0.6, 0.25, "NDC")
#kinGammaKey.setFont(PlotFonts.LEGEND_FONT)
#kinGammaKey.setColor(kinGamma.getColor())
#kinGammaKey.setKeyColor(kinGamma.getColor())
#
#kinAlpha = P1D(kinAlphaDPS)
#kinAlpha.setTitle("241Am &gamma;")
#kinAlpha.setColor(Color.RED)
#kinAlpha.setStyle("p")
#kinAlpha.setSymbol(2)
#kinAlpha.setSymbolSize(16)
#kinAlpha.setErrX(False)
#kinAlphaKey = JaKey(kinAlpha.getSymbol(), kinAlpha.getTitle(), 0.6, 0.3, "NDC")
#kinAlphaKey.setFont(PlotFonts.LEGEND_FONT)
#kinAlphaKey.setColor(kinAlpha.getColor())
#kinAlphaKey.setKeyColor(kinAlpha.getColor())
#
#kinNa22DPS = afrRun4.grabDPS("Kinetic/Decay_Comp#3")
#kinNa22 = P1D(kinNa22DPS)
#kinNa22.setTitle("22Na &gamma;")
#kinNa22.setColor(PlotColors.DARK_GREEN)
#kinNa22.setStyle("p")
#kinNa22.setSymbol(8)
#kinNa22.setSymbolSize(16)
#kinNa22.setErrX(False)
#kinNa22Key = JaKey(kinNa22.getSymbol(), kinNa22.getTitle(), 0.6, 0.35, "NDC")
#kinNa22Key.setFont(PlotFonts.LEGEND_FONT)
#kinNa22Key.setColor(kinNa22.getColor())
#kinNa22Key.setKeyColor(kinNa22.getColor())
#
#kinPlotter = HPlotJa("ZnWO4 Main Component Kinetic", 600, 600, 1, 1, True)
#kinPlotter.setGTitle("ZnWO_{4} Main Component Kinetic", PlotFonts.TITLE_FONT)
#kinPlotter.setAntiAlias(False)
#kinPlotter.visible(showFigures)
#kinPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
#kinPlotter.setRange(1, 1000, 10, 1000)
#kinPlotter.setLogScale(0, True)
#kinPlotter.setLogScale(1, True)
#kinPlotter.setTicFont(PlotFonts.TICK_FONT)
#kinPlotter.setShowStatBox(False)
#kinPlotter.showKey(False)
#kinPlotter.setNameX("Temperature (K)")
#kinPlotter.setNameY("Main Decay Time (&micro;s)")
#kinPlotter.draw(kinGamma)
#kinPlotter.draw(kinAlpha)
#kinPlotter.draw(kinNa22)
#kinPlotter.draw(kinGammaKey)
#kinPlotter.draw(kinAlphaKey)
#kinPlotter.draw(kinNa22Key)
#kinPlotter.draw(prelim)
#kinPlotter.update()
#
#pbKin = BeautifierFactory.beautifyHPlotJa(kinPlotter)
#kinPad11 = pbKin.pad(1, 1)
#kinLabelX11 = kinPad11.axisLabel(0)
#kinLabelX11.centerLabel()
#kinLabelX11.changeFont(PlotFonts.AXIS_LABEL_FONT)
#kinLabelY11 = kinPad11.axisLabel(1)
#kinLabelY11.centerLabel(-0.01)
#kinLabelY11.changeFont(PlotFonts.AXIS_LABEL_FONT)
#
#kinTickLabX11 = kinPad11.tickLabel(0)
#kinTickLabX11.axisDistance(0.0)
#kinTickLabX11.displayAsPowerOfTen()
#kinTickLabY11 = kinPad11.tickLabel(1)
#kinTickLabY11.axisDistance(-0.01)
#kinTickLabY11.removeNegativeZero()
#
#kinPlotter.update()
#if writeFigures:
#	for j in range(len(FileExtensions.FIG_TYPES)):
#		outFileName = "ZnWO4_Kinetic" + FileExtensions.FIG_TYPES[j]
#		kinPlotter.export(genPath + File.separator + outFileName)
#		print("Writting File : " + genPath + File.separator + outFileName)

if writeAida:
	print "\nWriting Aida File: " + treeName + ".aida"
	tree.commit()
print "That's All Folks !!!\n"
#if not showFigures:
exit()
